package io.github.maojian.bianrysearch;

import org.junit.Test;

/**
 * @Auther: jian.mao
 * @Date: 2022/6/7 09:20
 * @Description: 875. 爱吃香蕉的珂珂
 *
 *  https://leetcode.cn/problems/koko-eating-bananas/
 *
 */
public class Q875 {
    public int minEatingSpeed(int[] piles, int h) {
        int low = 1;
        int high = getHigh(piles);
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (consuming(mid, piles) > h) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }

    private int getHigh(int[] piles) {
        int high = 1;
        for (int pile : piles) {
            high = Math.max(high, pile);
        }
        return high;
    }

    /*
     * 获取当前速度下耗费时间
     */
    private int consuming(int mid, int[] piles) {
        int sum = 0;
        for (int pile : piles) {
            if (mid > pile) {
                sum++;
            } else {
                sum += (pile % mid == 0 ? pile / mid : pile / mid + 1);
            }
        }
        return sum;
    }

    @Test
    public void test() {
        int[] piles = new int[]{3,6,7,11};
        int h = 8;
        System.out.println(minEatingSpeed(piles, h));
    }

    @Test
    public void test01() {
        int[] piles = new int[]{30,11,23,4,20};
        int h = 5;
        System.out.println(minEatingSpeed(piles, h));
    }

    @Test
    public void test02() {
        int[] piles = new int[]{30,11,23,4,20};
        int h = 6;
        System.out.println(minEatingSpeed(piles, h));
    }
}
